package lizhe.dummynode;


import java.util.List;

public class MergeTwoLists {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        ListNode result = new ListNode();
        ListNode curr = result;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                curr.next = list1;
                list1 = list1.next;
            } else {
                curr.next = list2;
                list2 = list2.next;
            }
            curr = curr.next;
        }
        if (list1 != null) {
            result.next = list1;
        }
        if (list2 != null) {
            result.next = list2;
        }

        return result.next;

    }

    public static ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if (list1 == null)
            return list2;

        if (list2 == null)
            return list1;

        if (list1.val <= list2.val) {
            list1.next = mergeTwoLists2(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists2(list1, list2.next);
            return list2;
        }

    }

    public static void main(String[] args) {
        ListNode list1 = new ListNode(1);
        ListNode list12 = new ListNode(1);
        ListNode list22 = new ListNode(2);
        ListNode list3 = new ListNode(3);
        ListNode list4 = new ListNode(4);
        ListNode list42 = new ListNode(4);
        list1.next = list3;
        list3.next = list4;
        list12.next = list22;
        list22.next = list42;

        ListNode listNode = mergeTwoLists2(list1, list12);
        System.out.println(listNode);

    }
}
